<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAWork;
use App\Model\OAWorkLink;
use App\Model\OAWorkNode;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

//流程逻辑
class WorkLogic extends Controller
{
    private $state_list = [2=>'待开发',1=>'正常',0=>'禁止'];
    public $work_type_list = [
        1=>'项目',
        2=>'财务',
        3=>'休假',
        4=>'行政',
        5=>'加班',
        6=>'用车',
        7=>'考勤',
        8=>'物料',
        9=>'交通',
    ];
    //获取流程列表
    public function getList($input)
    {
        try{
        $query = OAWork::query();
        //流程名
        if(isset($input['name']) && !empty($input['name'])){
            $query->when($input['name'],function($q,$work_name){
                return $q->where('name','like','%'.$work_name.'%');
            });
        }
        //状态
        if(isset($input['status']) && !empty($input['status'])){
            $query->where('status',$input['status']);
        }

        if(isset($input['type']) && !empty($input['type'])){
            $query->where('type',$input['type']);
        }

        $list = $query->paginate($input['pagesize'],['*'])->toArray();

       // dd($query->toSql(),$query->getBindings());
        foreach ($list['data'] as &$item){
            $item['status'] = $this->state_list[$item['status']];
            $item['type'] = $this->work_type_list[$item['type']];
        }

         $list['work_state_list'] = $this->state_list;
         $list['work_type_list'] = $this->work_type_list;

        return $list;
        }catch(\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    public function addWork($params)
    {
        try{
            #1.添加主要信息
            $work_id = $this->saveMainInfo($params);

            #2.添加节点名称
            $node_list = $this->saveWorkNode($work_id,$params);

            #3.添加流程信息

            return $this->saveWorkLink($work_id,$node_list);

        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    //添加主要信息
    protected function saveMainInfo($params)
    {

        $positionList = $params['position'];
        $roleid = Arr::first($positionList);
        //dd($roleid);
        $insert_data = [
            'name'=>$params['name'],
            'roleid'=>$roleid,
            'status'=>$params['status'],
            'type'=>$params['type'],
            'desc'=>$params['desc'],
            'created_at'=>date('Y-m-d H:i:s'),
        ];

        return OAWork::query()->insertGetId($insert_data);
    }

    //添加流程节点名称
    protected function saveWorkNode($work_id,$params)
    {
        $node_length = count($params['position']);
        $node_ids = [];
        for($i = 0;$i < $node_length;$i++){
            $insert_data = [
                'work_id'=>$work_id,
                'roleid'=>$params['position'][$i],
//                'uid'=>$params['userlist'][$i],
            ];
            $node_ids[] = OAWorkNode::query()->insertGetId($insert_data);
        }

        return $node_ids;

    }

    //保存流程信息
    public function saveWorkLink($work_id,$node_list)
    {
        //[1,2,3,4,5,6]
        $len = count($node_list);
        for($i = 0;$i < $len;$i++){
            $pre_node = $node_list[$i];
            $next_id = $i + 1;
            $next_node = $next_id == $len ? 0 : $node_list[$next_id];
            $insert_data = [
                'work_id'=>$work_id,
                'pre_node'=>$pre_node,
                'next_node'=>$next_node
            ];

            OAWorkLink::query()->insert($insert_data);
        }

        return true;
    }

    //获取流程详情
    public function getWorkDetail($params)
    {
         $work = OAWork::query()->where('id',$params['id'])->first();

         $work_node = $work->work_node()->get()->toArray();

         $work_node = array_column($work_node,null,'id');

         $work_link = $work->work_link()->orderBy('id','ASC')->pluck('pre_node')->toArray();

        $commonLogic = new CommonLogic();

        //$all = $commonLogic->getAllRoleAndUser();//073182208373

        $workList = $userList = [];
         foreach ($work_link as $link){
             $workList[] = [
                 'id'=>$link,
                 'role'=>strval($work_node[$link]['roleid']),
                // 'uid'=>$work_node[$link]['uid'],
             ];
         }

         //$user_all = $all['user_all'];

         $work->workList = $workList;

         $work->workRow = count($workList);

         $work->id = $params['id'];

         $work->gsid = strval($work->gsid);

         $work->status = strval($work->status);

         $work->userList = $userList;

         return $work;
    }

    //修改流程
    public function editWorkInfo($params)
    {

        DB::beginTransaction();

        try{
            //修改基础信息
            $work = OAWork::query()->where('id',$params['id'])->first();

            $work->name = $params['name'];

            $work->desc = $params['desc'];

            $work->status = $params['status'];

            $work->save();

            //修改流程信息
            $workList = $params['workList'];

            $work_id_list = array_column($workList,'id');

            $work_node_list = $work->work_node()->pluck('id')->toArray();

            #1.新增怎么处理
            if(count($work_node_list) < $params['workRow']){
                //新增
                $newWorkId = [];
                foreach ($workList as $wk){
                    if($wk['id']) continue;
                    $newWorkId[] = OAWorkNode::query()->insertGetId([
                        'work_id'=>$params['id'],
                        'roleid'=>$wk['role'],
                    ]);
                }

               //throw new \Exception('新增流程: '.$newWorkId[0]);
                OAWorkLink::query()->where('work_id',$params['id'])->where('next_node',0)->update(['next_node'=>$newWorkId[0]]);
                $this->saveWorkLink($params['id'],$newWorkId);

            }elseif (count($work_node_list) > $params['workRow']){
                $work_id_difft = array_diff($work_node_list,$work_id_list);
                //删除不在的流程
                OAWorkNode::query()->where('work_id',$params['id'])->whereNotIn('id',$work_id_list)->delete();
                //如果删除的流程存在
                if($work_id_difft){
                    OAWorkLink::query()->where('work_id',$params['id'])->whereIn('pre_node',$work_id_difft)->delete();
                }
                $lastWorkId = array_pop($work_id_list);
                OAWorkLink::query()->where('work_id',$params['id'])->where('pre_node',$lastWorkId)->update(['next_node'=>0]);

            }else{

            }
            //更新操作
            foreach ($workList as $wk)
            {
                if($wk['id']) {
                    //更新
                    OAWorkNode::query()->where('id', $wk['id'])->update(['roleid' => $wk['role']]);
                }
            }

            DB::commit();

            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //删除流程
    public function delWork($input)
    {
       try{
           DB::beginTransaction();
           OAWork::query()->where('id',$input['id'])->delete();
           OAWorkLink::query()->where('work_id',$input['id'])->delete();
           OAWorkNode::query()->where('work_id',$input['id'])->delete();
           DB::commit();
           return true;
       } catch (\Exception $e){
           DB::rollBack();
           throw new \Exception($e->getMessage());
       }
    }

}
